﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cookie案例-记住用户名</title>
<script>
function setCookie(name, value, iDay)
{
	var oDate=new Date();
	
	oDate.setDate(oDate.getDate()+iDay);
	
	document.cookie=name+'='+value+';expires='+oDate;
}

function getCookie(name)
{
	//'username=abc; password=123456; aaa=123; bbb=4r4er'
	var arr=document.cookie.split('; ');
	var i=0;
	
	//arr->['username=abc', 'password=123456', ...]
	
	for(i=0;i<arr.length;i++)
	{
		//arr2->['username', 'abc']
		var arr2=arr[i].split('=');
		
		if(arr2[0]==name)
		{
			return arr2[1];
		}
	}
	
	return '';
}

function removeCookie(name)
{
	setCookie(name, '1', -1);
}

window.onload=function ()
{
	var oForm=document.getElementById('form1');
	var oUser=document.getElementsByName('user')[0];
	var oBtnClear=document.getElementsByTagName('a')[0];
	
	oForm.onsubmit=function () //当用户提交后,记录用户名
	{
		setCookie('user', oUser.value, 30);
	};
	
	oUser.value=getCookie('user'); //当用户打开页面后,用户名默认在
	
	oBtnClear.onclick=function () // 点击清除cookie
	{
		 removeCookie('user');
		oUser.value=''; // 有的value值去除
	};
};
</script>
</head>

<body>
<form id="form1" action="#">
	用户名：<input type="text" name="user" />
    密码：<input type="password" name="pass" />
    <input type="submit" value="登录" />
    <a href="javascript:;">清除记录</a>
</form>
</body>
</html>
